#!/bin/sh
# NEEDS sed,grep,zip,unzip

findTemplate() {
	templateName=$1
	for d in /usr/share/asgard/templates ~/.local/share/asgard/templates templates .
	do
		if stat "$d/$templateName" >/dev/null 2>&1
		then
			echo "$d/$templateName"
			return
		fi
	done
	return 1
}

set -e

# shellcheck disable=SC2010
years=$(ls Current/ | grep -E '^[0-9]{4}' -o | sort -u)

if [ -n "$years" ]
then
	mkdir -p tmp
	unzip diary.epub -d tmp
fi

spine=""
manifest=""

for year in $years
do
	echo year "$year"
	# shellcheck disable=SC2010
	files=$(ls | grep -E "^$year")

	# shellcheck disable=SC2086
	cat $files > "../tmp/$year.html"

	# todo hyphenate
	# https://github.com/hunspell/hyphen
	# https://github.com/hunspell/hyphen/blob/master/example.c
	# ./newscripts/hyph_en_GB.dic

	sed -i 's|<hr>|<hr/>|g' "tmp/$year.html"

	footer="</body></html>"
	if [ ! -e "tmp/OEBPS/Text/$year.xhtml" ]
	then
		header='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><title>'"$year"'</title><link href="../Styles/Style.css" rel="stylesheet" type="text/css"/></head><body><h1><a id="navPoint-'"$year"'">'"$year"'</a></h1>'
		chapter=$(printf "%s\n%s\n%s" "$header" "$(cat "tmp/$year.html")" "$footer")
	else
		sed -i -E 's$</(body|html)>$$' "tmp/OEBPS/Text/$year.xhtml"
		chapter=$(printf "%s\n%s\n%s" "$(cat "tmp/OEBPS/Text/$year.xhtml")" "$(cat "tmp/$year.html")" "$footer")
	fi
	echo "$chapter" > "tmp/OEBPS/Text/$year.xhtml"
done

# shellcheck disable=SC2010
years=$(ls tmp/OEBPS/Text/ | grep -E '^[0-9]{4}' -o | sort -u)
for year in $years
do
	manifest="$manifest\n\t\t<item href=\"Text/$year.xhtml\" id=\"$year.xhtml\" media-type=\"application/xhtml+xml\"/>"
	spine="$spine\n\t\t<itemref idref=\"$year.xhtml\"/>"
	
	cp "$(findTemplate content.opf.template)" tmp/OEBPS/content.opf
	sed -i "s|{{manifest}}|$manifest|" tmp/OEBPS/content.opf
	sed -i "s|{{spine}}|$spine|" tmp/OEBPS/content.opf

	toc="$toc\n\t\t<li><a href=\"$year.xhtml\">$year</a></li>"
	cp "$(findTemplate nav.xhtml.template)" tmp/OEBPS/Text/nav.xhtml
	sed -i "s|{{toc}}|$toc|" tmp/OEBPS/Text/nav.xhtml
done

rm diary.epub

cd tmp
zip -X ../diary.epub mimetype
zip -rg ../diary.epub META-INF
zip -rg ../diary.epub OEBPS
cd ..

rm -rf tmp
rm ./*.html
